<!DOCTYPE html>



  


<html class="theme-next mist use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.9.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Hexo, NexT">










<meta name="description" content="使用方法12345678910111213awk &apos;&amp;#123;pattern + action&amp;#125;&apos; &amp;#123;filenames&amp;#125;变量名	含义 ARGC	命令行变元个数 ARGV	命令行变元数组 FILENAME	当前输入文件名 FNR	当前文件中的记录号 FS	输入域分隔符，默认为一个空格 RS	输入记录分隔符 NF	当前记录里域个数 NR	到目前为止记录数 OFS	输出">
<meta property="og:type" content="article">
<meta property="og:title" content="awk">
<meta property="og:url" content="http://changyuan.github.io/2017/01/25/awk/index.html">
<meta property="og:site_name" content="Chang Crazy&#39;s Blog">
<meta property="og:description" content="使用方法12345678910111213awk &apos;&amp;#123;pattern + action&amp;#125;&apos; &amp;#123;filenames&amp;#125;变量名	含义 ARGC	命令行变元个数 ARGV	命令行变元数组 FILENAME	当前输入文件名 FNR	当前文件中的记录号 FS	输入域分隔符，默认为一个空格 RS	输入记录分隔符 NF	当前记录里域个数 NR	到目前为止记录数 OFS	输出">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2017-01-25T04:08:15.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="awk">
<meta name="twitter:description" content="使用方法12345678910111213awk &apos;&amp;#123;pattern + action&amp;#125;&apos; &amp;#123;filenames&amp;#125;变量名	含义 ARGC	命令行变元个数 ARGV	命令行变元数组 FILENAME	当前输入文件名 FNR	当前文件中的记录号 FS	输入域分隔符，默认为一个空格 RS	输入记录分隔符 NF	当前记录里域个数 NR	到目前为止记录数 OFS	输出">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Mist',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://changyuan.github.io/2017/01/25/awk/">





  <title>awk | Chang Crazy's Blog</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Chang Crazy's Blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">升级自己的操作系统</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-schedule">
          <a href="/schedule/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-calendar"></i> <br>
            
            日程表
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br>
            
            关于
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://changyuan.github.io/2017/01/25/awk/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="changyuan">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Chang Crazy's Blog">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">awk</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2017-01-25T12:08:15+08:00">
                2017-01-25
              </time>
            

            

            
          </span>

          

          
            
          

          
          

          
            <span class="post-meta-divider">|</span>
            <span class="page-pv"><i class="fa fa-file-o"></i>
            <span class="busuanzi-value" id="busuanzi_value_page_pv"></span>
            </span>
          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h2 id="使用方法"><a href="#使用方法" class="headerlink" title="使用方法"></a>使用方法</h2><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">awk <span class="string">'&#123;pattern + action&#125;'</span> &#123;filenames&#125;</span><br><span class="line"></span><br><span class="line">变量名	含义 </span><br><span class="line">ARGC	命令行变元个数 </span><br><span class="line">ARGV	命令行变元数组 </span><br><span class="line">FILENAME	当前输入文件名 </span><br><span class="line">FNR	当前文件中的记录号 </span><br><span class="line">FS	输入域分隔符，默认为一个空格 </span><br><span class="line">RS	输入记录分隔符 </span><br><span class="line">NF	当前记录里域个数 </span><br><span class="line">NR	到目前为止记录数 </span><br><span class="line">OFS	输出域分隔符 </span><br><span class="line">ORS	输出记录分隔符</span><br></pre></td></tr></table></figure>
<a id="more"></a>
<h2 id="调用awk"><a href="#调用awk" class="headerlink" title="调用awk"></a>调用awk</h2><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br><span class="line">142</span><br><span class="line">143</span><br><span class="line">144</span><br><span class="line">145</span><br><span class="line">146</span><br><span class="line">147</span><br><span class="line">148</span><br><span class="line">149</span><br><span class="line">150</span><br><span class="line">151</span><br><span class="line">152</span><br><span class="line">153</span><br><span class="line">154</span><br><span class="line">155</span><br><span class="line">156</span><br><span class="line">157</span><br><span class="line">158</span><br><span class="line">159</span><br><span class="line">160</span><br><span class="line">161</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line">1、awk <span class="string">'/101/'</span>               file 显示文件file中包含101的匹配行。 </span><br><span class="line">   awk <span class="string">'/101/,/105/'</span>         file </span><br><span class="line">   awk <span class="string">'$1 == 5'</span>             file </span><br><span class="line">   awk <span class="string">'$1 == "CT"'</span>          file 注意必须带双引号 </span><br><span class="line">   awk <span class="string">'$1 * $2 &gt;100 '</span>       file  </span><br><span class="line">   awk <span class="string">'$2 &gt;5 &amp;&amp; $2&lt;=15'</span>     file</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">2、awk <span class="string">'&#123;print NR,NF,$1,$NF,&#125;'</span> file 显示文件file的当前记录号、域数和每一行的第一个和最后一个域。 </span><br><span class="line">   awk <span class="string">'/101/ &#123;print $1,$2 + 10&#125;'</span> file 显示文件file的匹配行的第一、二个域加10。 </span><br><span class="line">   awk <span class="string">'/101/ &#123;print $1$2&#125;'</span>  file </span><br><span class="line">   awk <span class="string">'/101/ &#123;print $1 $2&#125;'</span> file 显示文件file的匹配行的第一、二个域，但显示时域中间没有分隔符。</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">3、df | awk <span class="string">'$4&gt;1000000 '</span>         通过管道符获得输入，如：显示第4个域满足条件的行。</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">4、awk -F <span class="string">"|"</span> <span class="string">'&#123;print $1&#125;'</span>   file 按照新的分隔符“|”进行操作。 </span><br><span class="line">   awk  <span class="string">'BEGIN &#123; FS="[: \t|]" &#125; </span></span><br><span class="line"><span class="string">   &#123;print $1,$2,$3&#125;'</span> 	     file 通过设置输入分隔符（FS=<span class="string">"[: \t|]"</span>）修改输入分隔符。 </span><br><span class="line"></span><br><span class="line">   Sep=<span class="string">"|"</span> </span><br><span class="line">   awk -F <span class="variable">$Sep</span> <span class="string">'&#123;print $1&#125;'</span>  file 按照环境变量Sep的值做为分隔符。    </span><br><span class="line">   awk -F <span class="string">'[ :\t|]'</span> <span class="string">'&#123;print $1&#125;'</span> file 按照正则表达式的值做为分隔符，这里代表空格、:、TAB、|同时做为分隔符。 </span><br><span class="line">   awk -F <span class="string">'[][]'</span>    <span class="string">'&#123;print $1&#125;'</span> file 按照正则表达式的值做为分隔符，这里代表[、]</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">5、awk -f awkfile 	     file 通过文件awkfile的内容依次进行控制。 </span><br><span class="line">   cat awkfile </span><br><span class="line">/101/&#123;<span class="built_in">print</span> <span class="string">"\047 Hello! \047"</span>&#125; --遇到匹配行以后打印 <span class="string">' Hello! '</span>.\047代表单引号。 </span><br><span class="line">&#123;<span class="built_in">print</span> <span class="variable">$1</span>,<span class="variable">$2</span>&#125;                   --因为没有模式控制，打印每一行的前两个域。</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">6、awk <span class="string">'$1 ~ /101/ &#123;print $1&#125;'</span> file 显示文件中第一个域匹配101的行（记录）。</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">7、awk   <span class="string">'BEGIN &#123; OFS="%"&#125; </span></span><br><span class="line"><span class="string">   &#123;print $1,$2&#125;'</span>           file 通过设置输出分隔符（OFS=<span class="string">"%"</span>）修改输出格式。</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">8、awk   <span class="string">'BEGIN &#123; max=100 ;print "max=" max&#125;             BEGIN 表示在处理任意行之前进行的操作。 </span></span><br><span class="line"><span class="string">   &#123;max=($1 &gt;max ?$1:max); print $1,"Now max is "max&#125;'</span> file 取得文件第一个域的最大值。 </span><br><span class="line">   （表达式1?表达式2:表达式3 相当于： </span><br><span class="line">   <span class="keyword">if</span> (表达式1) </span><br><span class="line">       表达式2 </span><br><span class="line">   <span class="keyword">else</span> </span><br><span class="line">       表达式3 </span><br><span class="line">   awk <span class="string">'&#123;print ($1&gt;4 ? "high "$1: "low "$1)&#125;'</span> file </span><br><span class="line"></span><br><span class="line"></span><br><span class="line">9、awk <span class="string">'$1 * $2 &gt;100 &#123;print $1&#125;'</span> file 显示文件中第一个域匹配101的行（记录）。</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">10、awk <span class="string">'&#123;$1 == '</span>Chi<span class="string">' &#123;$3 = '</span>China<span class="string">'; print&#125;'</span> file 找到匹配行后先将第3个域替换后再显示该行（记录）。 </span><br><span class="line">    awk <span class="string">'&#123;$7 %= 3; print $7&#125;'</span>  file 将第7域被3除，并将余数赋给第7域再打印。</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">11、awk <span class="string">'/tom/ &#123;wage=$2+$3; printf wage&#125;'</span> file 找到匹配行后为变量wage赋值并打印该变量。</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">12、awk <span class="string">'/tom/ &#123;count++;&#125;  </span></span><br><span class="line"><span class="string">         END &#123;print "tom was found "count" times"&#125;'</span> file END表示在所有输入行处理完后进行处理。</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">13、awk <span class="string">'gsub(/\$/,"");gsub(/,/,""); cost+=$4; </span></span><br><span class="line"><span class="string">         END &#123;print "The total is $" cost&gt;"filename"&#125;'</span>    file gsub函数用空串替换$和,再将结果输出到filename中。 </span><br><span class="line">    1 2 3 <span class="variable">$1</span>,200.00 </span><br><span class="line">    1 2 3 <span class="variable">$2</span>,300.00 </span><br><span class="line">    1 2 3 <span class="variable">$4</span>,000.00 </span><br><span class="line"></span><br><span class="line">    awk <span class="string">'&#123;gsub(/\$/,"");gsub(/,/,""); </span></span><br><span class="line"><span class="string">    if ($4&gt;1000&amp;&amp;$4&lt;2000) c1+=$4; </span></span><br><span class="line"><span class="string">    else if ($4&gt;2000&amp;&amp;$4&lt;3000) c2+=$4; </span></span><br><span class="line"><span class="string">    else if ($4&gt;3000&amp;&amp;$4&lt;4000) c3+=$4; </span></span><br><span class="line"><span class="string">    else c4+=$4; &#125; </span></span><br><span class="line"><span class="string">    END &#123;printf  "c1=[%d];c2=[%d];c3=[%d];c4=[%d]\n",c1,c2,c3,c4&#125;"'</span> file </span><br><span class="line">    通过<span class="keyword">if</span>和<span class="keyword">else</span> <span class="keyword">if</span>完成条件语句 </span><br><span class="line"></span><br><span class="line">    awk <span class="string">'&#123;gsub(/\$/,"");gsub(/,/,""); </span></span><br><span class="line"><span class="string">    if ($4&gt;3000&amp;&amp;$4&lt;4000) exit; </span></span><br><span class="line"><span class="string">    else c4+=$4; &#125; </span></span><br><span class="line"><span class="string">    END &#123;printf  "c1=[%d];c2=[%d];c3=[%d];c4=[%d]\n",c1,c2,c3,c4&#125;"'</span> file </span><br><span class="line">    通过<span class="built_in">exit</span>在某条件时退出，但是仍执行END操作。 </span><br><span class="line">    awk <span class="string">'&#123;gsub(/\$/,"");gsub(/,/,""); </span></span><br><span class="line"><span class="string">    if ($4&gt;3000) next; </span></span><br><span class="line"><span class="string">    else c4+=$4; &#125; </span></span><br><span class="line"><span class="string">    END &#123;printf  "c4=[%d]\n",c4&#125;"'</span> file </span><br><span class="line">    通过next在某条件时跳过该行，对下一行执行操作。 </span><br><span class="line"></span><br><span class="line"></span><br><span class="line">14、awk <span class="string">'&#123; print FILENAME,$0 &#125;'</span> file1 file2 file3&gt;fileall 把file1、file2、file3的文件内容全部写到fileall中，格式为 </span><br><span class="line">    打印文件并前置文件名。</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">15、awk <span class="string">' $1!=previous &#123; close(previous); previous=$1 &#125;    </span></span><br><span class="line"><span class="string">    &#123;print substr($0,index($0," ") +1)&gt;$1&#125;'</span> fileall 把合并后的文件重新分拆为3个文件。并与原文件一致。</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">16、awk <span class="string">'BEGIN &#123;"date"|getline d; print d&#125;'</span>         通过管道把date的执行结果送给getline，并赋给变量d，然后打印。 </span><br><span class="line"></span><br><span class="line"></span><br><span class="line">17、awk <span class="string">'BEGIN &#123;system("echo \"Input your name:\\c\""); getline d;print "\nYour name is",d,"\b!\n"&#125;'</span> </span><br><span class="line">    通过getline命令交互输入name，并显示出来。 </span><br><span class="line">    awk <span class="string">'BEGIN &#123;FS=":"; while(getline&lt; "/etc/passwd" &gt;0) &#123; if($1~"050[0-9]_") print $1&#125;&#125;'</span> </span><br><span class="line">    打印/etc/passwd文件中用户名包含050x_的用户名。 </span><br><span class="line"></span><br><span class="line">18、awk <span class="string">'&#123; i=1;while(i&lt;NF) &#123;print NF,$i;i++&#125;&#125;'</span> file 通过<span class="keyword">while</span>语句实现循环。 </span><br><span class="line">    awk <span class="string">'&#123; for(i=1;i&lt;NF;i++) &#123;print NF,$i&#125;&#125;'</span>   file 通过<span class="keyword">for</span>语句实现循环。     </span><br><span class="line">    <span class="built_in">type</span> file|awk -F <span class="string">"/"</span> <span class="string">' </span></span><br><span class="line"><span class="string">    &#123; for(i=1;i&lt;NF;i++) </span></span><br><span class="line"><span class="string">    &#123; if(i==NF-1) &#123; printf "%s",$i &#125; </span></span><br><span class="line"><span class="string">    else &#123; printf "%s/",$i &#125; &#125;&#125;'</span>               显示一个文件的全路径。 </span><br><span class="line">    用<span class="keyword">for</span>和<span class="keyword">if</span>显示日期 </span><br><span class="line">    awk  <span class="string">'BEGIN &#123; </span></span><br><span class="line"><span class="string">for(j=1;j&lt;=12;j++) </span></span><br><span class="line"><span class="string">&#123; flag=0; </span></span><br><span class="line"><span class="string">  printf "\n%d月份\n",j; </span></span><br><span class="line"><span class="string">        for(i=1;i&lt;=31;i++) </span></span><br><span class="line"><span class="string">        &#123; </span></span><br><span class="line"><span class="string">        if (j==2&amp;&amp;i&gt;28) flag=1; </span></span><br><span class="line"><span class="string">        if ((j==4||j==6||j==9||j==11)&amp;&amp;i&gt;30) flag=1; </span></span><br><span class="line"><span class="string">        if (flag==0) &#123;printf "%02d%02d ",j,i&#125; </span></span><br><span class="line"><span class="string">        &#125; </span></span><br><span class="line"><span class="string">&#125; </span></span><br><span class="line"><span class="string">&#125;'</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">19、在awk中调用系统变量必须用单引号，如果是双引号，则表示字符串 </span><br><span class="line">Flag=abcd </span><br><span class="line">awk <span class="string">'&#123;print '</span><span class="variable">$Flag</span><span class="string">'&#125;'</span>   结果为abcd </span><br><span class="line">awk <span class="string">'&#123;print  "$Flag"&#125;'</span>   结果为<span class="variable">$Flag</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment"># 对a.txt文件的第四个域进行求和！</span></span><br><span class="line">awk <span class="string">'BEGIN&#123;total=0&#125;&#123;total+=$4&#125;END&#123;print total&#125;'</span> a.txt</span><br><span class="line"></span><br><span class="line"><span class="comment"># 打印所有以模式no或so开头的行。</span></span><br><span class="line">awk <span class="string">'/^(no|so)/'</span> <span class="built_in">test</span>  </span><br><span class="line"></span><br><span class="line"><span class="comment"># 如果记录以n或s开头，就打印这个记录。</span></span><br><span class="line">awk <span class="string">'/^[ns]/&#123;print $1&#125;'</span> <span class="built_in">test</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># 如果第一个域以两个数字结束就打印这个记录。</span></span><br><span class="line">awk <span class="string">'$1 ~/[0-9][0-9]$/(print $1&#125;'</span> <span class="built_in">test</span> </span><br><span class="line"></span><br><span class="line"><span class="comment"># 如果第一个或等于100或者第二个域小于50，则打印该行。</span></span><br><span class="line">awk <span class="string">'$1 == 100 || $2 &lt; 50'</span> <span class="built_in">test</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># 如果第一个域不等于10就打印该行。</span></span><br><span class="line">awk <span class="string">'$1 != 10'</span> <span class="built_in">test</span></span><br><span class="line"></span><br><span class="line"><span class="comment">#如果记录包含正则表达式test，则第一个域加10并打印出来。</span></span><br><span class="line">awk <span class="string">'/test/&#123;print $1 + 10&#125;'</span> <span class="built_in">test</span> </span><br><span class="line"></span><br><span class="line"><span class="comment">#如果第一个域大于5则打印问号后面的表达式值，否则打印冒号后面的表达式值。</span></span><br><span class="line">awk <span class="string">'&#123;print ($1 &gt; 5 ? "ok "$1: "error"$1)&#125;'</span> <span class="built_in">test</span> </span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment">#打印以正则表达式root开头的记录到以正则表达式mysql开头的记录范围内的所有记录。如果找到一个新的正则表达式root开头的记 录，则继续打印直到下一个以正则表达式mysql开头的记录为止，或到文件末尾。</span></span><br><span class="line">awk <span class="string">'/^root/,/^mysql/'</span> <span class="built_in">test</span></span><br></pre></td></tr></table></figure>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br></pre></td><td class="code"><pre><span class="line"># 一个示例</span><br><span class="line">set -e</span><br><span class="line">login=&quot;-h192.168.1.70 -P3306 -uroot -proot&quot;</span><br><span class="line">#读数据</span><br><span class="line">databases=$(mysql $&#123;login&#125; -N -e &quot;show databases like &apos;pre_%&apos;;&quot;)</span><br><span class="line">if [ -e datasAll.txt ]; then</span><br><span class="line">    cat /dev/null &gt;datasAll.txt</span><br><span class="line">fi</span><br><span class="line">for i in $&#123;databases&#125;</span><br><span class="line">do</span><br><span class="line">    echo $&#123;i&#125; &gt;&gt;log.txt</span><br><span class="line">    tables=$(mysql $&#123;login&#125; -N -e &quot;use $&#123;i&#125;; show tables;&quot;)</span><br><span class="line">    for j in $&#123;tables&#125;</span><br><span class="line">    do</span><br><span class="line">        mysql $&#123;login&#125; -N --default-character-set=utf8 -e &quot;use $&#123;i&#125;; select uid, income, spend, create_at from $&#123;j&#125;&quot; &gt;&gt;datasAll.txt</span><br><span class="line">    done</span><br><span class="line">done</span><br><span class="line">#统计数据</span><br><span class="line">echo &apos;--&gt;step 1&apos; &gt;&gt;log.txt</span><br><span class="line">grep &quot;2014-&quot; datasAll.txt &gt;datas2014.txt</span><br><span class="line">echo &apos;--&gt;step 2&apos; &gt;&gt;log.txt</span><br><span class="line">awk &apos;BEGIN&#123;FS=&quot;\t&quot;;OFS=&quot;\t&quot;;&#125;&#123;income[$1]+=$2;outlays[$1]+=$3;&#125;END&#123;for(key in income)&#123;print key,income[key],outlays[key] &gt;&quot;sumAll.txt&quot;&#125;&#125;&apos; datasAll.txt</span><br><span class="line">echo &apos;--&gt;step 3&apos; &gt;&gt;log.txt</span><br><span class="line">awk &apos;BEGIN&#123;FS=&quot;\t&quot;;OFS=&quot;\t&quot;;&#125;&#123;income[$1]+=$2;outlays[$1]+=$3;&#125;END&#123;for(key in income)&#123;print key,income[key],outlays[key] &gt;&quot;sum2014.txt&quot;&#125;&#125;&apos; datas2014.txt</span><br><span class="line">echo &apos;--&gt;step 4&apos; &gt;&gt;log.txt</span><br><span class="line">awk &apos;BEGIN&#123;FS=&quot;\t&quot;;OFS=&quot;\t&quot;;&#125;&#123;if(NR==FNR)&#123;uid[$1]=$2&#125;else if(NR&gt;FNR)&#123;if($1 in uid)&#123;margin=uid[$1]+$3;if(margin&gt;0)&#123;print $1,$2+$3-margin,margin &gt;&quot;baseDatas.txt&quot;&#125;&#125;&#125;&#125;&apos; sum2014.txt sumAll.txt</span><br><span class="line"></span><br><span class="line">#清理数据</span><br><span class="line">echo &apos;--&gt;step 6&apos; &gt;&gt;log.txt</span><br><span class="line">rm -f datasAll.txt sumAll.txt datas2014.txt sum2014.txt log.txt</span><br><span class="line">#baseDatas.txt : 用户ID | 更新后摇豆总结余 | 2014年摇豆总结余 </span><br><span class="line"></span><br><span class="line">echo &apos;--&gt;OVER&apos; &gt;&gt;log.txt</span><br></pre></td></tr></table></figure>
      
    </div>
    
    
    

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>分享即是成长</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/images/wechat-reward-image.png" alt="changyuan 微信支付">
        <p>微信支付</p>
      </div>
    

    

    

  </div>
</div>

      </div>
    

    
      <div>
        <ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者：</strong>
    changyuan
  </li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="http://changyuan.github.io/2017/01/25/awk/" title="awk">http://changyuan.github.io/2017/01/25/awk/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>
    本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/3.0/" rel="external nofollow" target="_blank">CC BY-NC-SA 3.0</a> 许可协议。转载请注明出处！
  </li>
</ul>

      </div>
    

    <footer class="post-footer">
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2017/01/25/js-now-exec-func/" rel="next" title="javascript立即执行函数">
                <i class="fa fa-chevron-left"></i> javascript立即执行函数
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2017/03/15/login-more/" rel="prev" title="关于登陆的那些事">
                关于登陆的那些事 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image" src="/images/avatar.jpg" alt="changyuan">
            
              <p class="site-author-name" itemprop="name">changyuan</p>
              <p class="site-description motion-element" itemprop="description">不断升级自己的操作系统</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">69</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">1</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">26</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/changyuan" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-fab fa-github"></i>GitHub</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://twitter.com/changocean1" target="_blank" title="Twitter">
                      
                        <i class="fa fa-fw fa-fab fa-twitter"></i>Twitter</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="http://weibo.com/changyuan2011" target="_blank" title="Weibo">
                      
                        <i class="fa fa-fw fa-fab fa-weibo"></i>Weibo</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://www.douban.com/people/changyuanyuan" target="_blank" title="Zhihu">
                      
                        <i class="fa fa-fw fa-fab fa-quora"></i>Zhihu</a>
                  </span>
                
            </div>
          

          
          

          
          
            <div class="links-of-blogroll motion-element links-of-blogroll-inline">
              <div class="links-of-blogroll-title">
                <i class="fa  fa-fw fa-link"></i>
                Links
              </div>
              <ul class="links-of-blogroll-list">
                
                  <li class="links-of-blogroll-item">
                    <a href="http://weibo.com/changyuan2011" title="Weibo" target="_blank">Weibo</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://github.com/changyuan" title="GitHub" target="_blank">GitHub</a>
                  </li>
                
              </ul>
            </div>
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#使用方法"><span class="nav-number">1.</span> <span class="nav-text">使用方法</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#调用awk"><span class="nav-number">2.</span> <span class="nav-text">调用awk</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2023</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">changyuan</span>

  
</div>









<!-- 网站运行时间的设置 -->
<span id="timeDate">载入天数...</span>
<span id="times">载入时分秒...</span>
<script>
    var now = new Date();
    function createtime() {
        var grt= new Date("08/08/2014 00:00:00");
        now.setTime(now.getTime()+250);
        days = (now - grt ) / 1000 / 60 / 60 / 24; dnum = Math.floor(days);
        hours = (now - grt ) / 1000 / 60 / 60 - (24 * dnum); hnum = Math.floor(hours);
        if(String(hnum).length ==1 ){hnum = "0" + hnum;} minutes = (now - grt ) / 1000 /60 - (24 * 60 * dnum) - (60 * hnum);
        mnum = Math.floor(minutes); if(String(mnum).length ==1 ){mnum = "0" + mnum;}
        seconds = (now - grt ) / 1000 - (24 * 60 * 60 * dnum) - (60 * 60 * hnum) - (60 * mnum);
        snum = Math.round(seconds); if(String(snum).length ==1 ){snum = "0" + snum;}
        document.getElementById("timeDate").innerHTML = "本站已运行 "+dnum+" 天 ";
        document.getElementById("times").innerHTML = hnum + " 小时 " + mnum + " 分 " + snum + " 秒.";
    }
setInterval("createtime()",250);
</script>

        
<div class="busuanzi-count">
  <script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv">
      <i class="fa fa-user"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
      
    </span>
  

  
    <span class="site-pv">
      <i class="fa fa-eye"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
      
    </span>
  
</div>








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  

  

  

  

</body>
</html>
